﻿using System;
using System.Web;
//引入正则表达式命名空间
using System.Text;
using System.Data;
using System.Linq;

namespace msBsc.WebUi
{
    public partial class mfCustOrder : msBsc.Cls.mbPCustom
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BoundFromProvince();
                ShowData();

            }
        }


        private void BoundFromProvince()
        {
            using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
            {
                string strSql = "SELECT * FROM BSE_PROVINCE ";

                DataSet ds = oCDbAccess.QueryBySQL(strSql);
                this.BoundComboBox("dplPROVINCE_ID", ds, "PROVINCE_NME", "PROVINCE_ID", "", "", true);
            }
        }

        private void BoundFromCity(string strFatherId)
        {
            using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
            {
                string strSql = "SELECT * FROM BSE_PROVINCE_CITY WHERE (FATHER_ID='" + strFatherId + "')";

                DataSet ds = oCDbAccess.QueryBySQL(strSql);
                this.BoundComboBox("dplCITY_ID", ds, "CITY_NME", "CITY_ID", "", "", true);
                BoundArea("");
            }
        }

        private void BoundArea(string strFatherId)
        {
            using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
            {
                string strSql = "SELECT * FROM BSE_PROVINCE_CITY_AREA WHERE (FATHER_ID='" + strFatherId + "')";

                DataSet ds = oCDbAccess.QueryBySQL(strSql);
                this.BoundComboBox("dplAREA_ID", ds, "AREA_NME", "AREA_ID", "", "", true);
            }
        }

        //s=0,为直接购买的，s=1为购物车，g为货物ID，b为货物购物车ID，q为数量,p1规格1的值,p省份
        private string s = "", g = "", b = "", p1 = "", p2 = "",p="";
        private int q = 0;
        private DataSet dsList = null;
        private DataSet dsAcpList = null;
        private void GetFormParamByStr()
        {
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("p")))
            {
                p = this.Request.QueryString.Get("p");
            }
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("s")))
            {
                s = this.Request.QueryString.Get("s");
            }
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("g")))
            {
                g = this.Request.QueryString.Get("g");
            }
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("b")))
            {
                b = this.Request.QueryString.Get("b");
            }
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("q")))
            {
                if (!int.TryParse(this.Request.QueryString.Get("q"), out q))
                {
                    q = 1;
                }
            }
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("p1")))
            {
                p1 = this.Request.QueryString.Get("p1");
            }
            if (!string.IsNullOrEmpty(this.Request.QueryString.Get("p2")))
            {
                p2 = this.Request.QueryString.Get("p2");
            }
        }
        public string strReceiveAddrHtml = @"<p><span style="" font-weight:bold;"">收货人：</span><span id=""spnRecAddrSel1""></span></p><p><span style="" font-weight:bold;"">收货地址：</span><span id=""spnRecAddrSel2""></span></p>";
        private void ShowData()
        {
            GetFormParamByStr();
            if (string.IsNullOrEmpty(s) || s != "0" && s != "1")
            {
                this.ToErrPage("当前没有找到需要下单的货品，请返回重新选择！");
                return;
            }
            using (msBsc.AppLogic.DataAlc.CBizShpCustomerInfo ocust = new AppLogic.DataAlc.CBizShpCustomerInfo())
            {
                int iUserScoreQty = ocust.GetUserScoreAllowUseQty(msBsc.SvRef.UserInfo.Operator);
                this.ExecJScript("$('#spnAllowUseScore').html('" + iUserScoreQty.ToString() + "');");
            }

            using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo objgoods = new AppLogic.DataAlc.CBizShpGoodsInfo())
            {
                if (dsAcpList == null)
                {
                    using (msBsc.AppLogic.DataAlc.CBizShpCustomerReceipt odataobj = new AppLogic.DataAlc.CBizShpCustomerReceipt())
                    {
                        dsAcpList = odataobj.SelectByUserNme(msBsc.SvRef.UserInfo.Operator);
                    }
                }
                string strPid = p;
                if (dsAcpList.Tables[0].Rows.Count > 0)
                {
                    DataRow[] arrrowtm = dsAcpList.Tables[0].Select("IS_DEFAULT=1");
                    DataRow draddrtm;
                    if (arrrowtm.Length > 0)
                    {
                        draddrtm = arrrowtm[0];
                    }
                    else
                    {
                        draddrtm = dsAcpList.Tables[0].Rows[0];
                    }
                    strPid = draddrtm["PROVINCE_ID"].ToString();

                    //显示默认收货地址
                    string strtel = draddrtm["PHONE_NO"].ToString();
                    if (strtel == string.Empty)
                    {
                        strtel += draddrtm["AREA_CODE"].ToString() + "-" + draddrtm["LANDLINE_NO"].ToString() + "-" + draddrtm["EXTENSION_NO"].ToString();
                    }
                    else if (draddrtm["LANDLINE_NO"].ToString() != string.Empty)
                    {
                        strtel += "," + draddrtm["AREA_CODE"].ToString() + "-" + draddrtm["LANDLINE_NO"].ToString() + "-" + draddrtm["EXTENSION_NO"].ToString();
                    }

                    //bool blchecked = (draddrtm["IS_DEFAULT"].ToString() == "True" && strSelId == string.Empty || draddrtm["RECE_ADDRESS_ID"].ToString() == strSelId);
                    string strAddrFull = draddrtm["ZONE_DESC"].ToString() + draddrtm["STREET_ADDRESS"].ToString();
                    strtel = draddrtm["RECEIPT_NME"].ToString() + strtel;

                    strReceiveAddrHtml = @"<p><span style="" font-weight:bold;"">收货人：</span><span id=""spnRecAddrSel1"">" + strtel + @"</span></p><p><span style="" font-weight:bold;"">收货地址：</span><span id=""spnRecAddrSel2"">" + strAddrFull + @"</span></p>";

                    this.ExecJScript("$('#txtRecAddrId').val('" + draddrtm["RECE_ADDRESS_ID"].ToString() + "');");
                }
                dsList = objgoods.SelectGoodsForConfirmOrder(g, b, s, p1, p2, q, strPid);
                if (dsList.Tables[0].Rows.Count <= 0)
                {
                    this.ToErrPage("当前没有找到需要下单的货品，可能是选择的商品已失效或库存不足，请返回重新选择！");
                    return;
                }

                DataRow[] arrrowtem2 = dsList.Tables[0].Select("IS_DEL='1'");
                if (arrrowtem2.Length > 0)
                {
                    this.ToErrPage("商品已失效或库存不足，无法确认订单，请返回重新选择！");
                    //this.ExecJScript("$('#divErrShow').html('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson("商品已失效或库存不足，无法确认订单，请返回重新选择！") + "');");
                }

                this.ExecJScript("$('#txtGoodsId').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(g) + "');");
                this.ExecJScript("$('#txtCartId').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(b) + "');");
                this.ExecJScript("$('#txtSrcT').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(s) + "');");
                this.ExecJScript("$('#txtPubNId1').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(p1) + "');");
                this.ExecJScript("$('#txtPubNId2').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(p2) + "');");
                this.ExecJScript("$('#txtBuyQty').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(q.ToString()) + "');");
                this.ExecJScript("$('#txtPlaceId').val('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(strPid) + "');");

                ShowPayAmt();
                //loadGoodsList(g, b, s, p1, p2, q, strPid);


            }
        }

        public string GetGoodsListHtml()
        {
            if (dsList == null)
            {
                using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo objgoods = new AppLogic.DataAlc.CBizShpGoodsInfo())
                {
                    dsList = objgoods.SelectGoodsForConfirmOrder(g, b, s, p1, p2, q, "");
                }
            }
            System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();

            dsList.Tables[0].DefaultView.Sort = "COMM_TENANT_ID ASC";
            int icount=dsList.Tables[0].DefaultView.Count;
            decimal decshopLgisAmt = 0M, decshoptotallAmt = 0M, decchargeAmt=0M;
            for (int i = 0; i < icount; i++)
            {
                if (i == 0 || i > 0 && dsList.Tables[0].DefaultView[i-1]["COMM_TENANT_ID"].ToString() != dsList.Tables[0].DefaultView[i]["COMM_TENANT_ID"].ToString())
                {
                    decshopLgisAmt = 0M;
                    decshoptotallAmt = 0M;
                    sbHtml.Append(@"<div class=""floor cust-order""  shop-id="""+dsList.Tables[0].DefaultView[i]["COMM_TENANT_ID"].ToString()+@"""><div class=""order-title""><p><span style="" font-weight:bold;"">店铺：</span>" + dsList.Tables[0].DefaultView[i]["COMM_TENANT_NME"].ToString() + @"</p></div><ul  class=""goods-list"">");
                }
                DataRow drtm = dsList.Tables[0].DefaultView[i].Row;
                if ((decimal)drtm["FREIGHT"] > decshopLgisAmt)
                {
                    decshopLgisAmt = (decimal)drtm["FREIGHT"];
                }
                decshoptotallAmt += (decimal)drtm["GOODS_AMT"];

                sbHtml.Append(@"<li><img alt="""" src=""" + drtm["IMG_URL"].ToString() + @" 210x210img.jpg"" /><div class=""goods-info"">
                        <p class=""goods-amt""><em style=""color:#888;"">" + ((int)drtm["GOODS_STRIKE_SCORE"] == 0 ? "" : "(换购积分" + drtm["GOODS_STRIKE_SCORE"].ToString() + "点)") + @"</em> ￥<em>" + drtm["GOODS_STRIKE_PRICE"].ToString() + @"</em><span> × " + drtm["GOODS_QTY"].ToString() + @"</span></p>
                        <p>" + drtm["GOODS_NME"].ToString() + @"</p>
                        <p style=""color:#888;"">" + drtm["NORMS_DESC"].ToString() + @"</p></div><div class=""clear""></div></li> ");
                if (icount == i + 1 || i > 0 && icount > i + 1 && dsList.Tables[0].DefaultView[i + 1]["COMM_TENANT_ID"].ToString() != dsList.Tables[0].DefaultView[i]["COMM_TENANT_ID"].ToString())
                {
                    sbHtml.Append(@"</ul><div class=""order-title""><textarea rows=""2""  placeholder=""给卖家留言："" ></textarea></div>
        <div class=""order-title goods-amt"" ><p><span >运费（快递）：</span>￥<em class=""shop-logisamt"">" + (decshopLgisAmt).ToString() + @"</em></p></div>
        <div class=""order-title goods-amt"" ><p><span >店铺合计(含运费)：</span>￥<em class=""shop-totallamt"">" + (decshopLgisAmt + decshoptotallAmt).ToString() + @"</em></p></div>
        </div>");
                    decchargeAmt += (decshopLgisAmt + decshoptotallAmt);
                }
            }

            this.ExecJScript("$('#spnPAYABLE_AMT').html('" + decchargeAmt.ToString() + "');");
            this.ExecJScript("$('#J_ActualFee').html('" + decchargeAmt.ToString() + "');"); 
             
            return sbHtml.ToString();
        }

        private string strcalljs = "";
//        private void loadGoodsList(string strGoodsId, string strBuyIds, string strSrcType, string strP1, string strP2, int intQ, string strProvince)
//        {
//            if (dsList == null)
//            {
//                using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo objgoods = new AppLogic.DataAlc.CBizShpGoodsInfo())
//                {
//                    dsList = objgoods.SelectGoodsForConfirmOrder(strGoodsId, strBuyIds, strSrcType, strP1, strP2, intQ, strProvince);
//                }
//            }

//            string strjsontem1 = msBsc.AppLogic.Cfg.HttpTools.GetJsonByTable(dsList.Tables[0], "", "COMM_TENANT_ID,COMM_TENANT_NME,USER_NME"
//                    , 1
//                    , 1111
//                    , "");
//            this.ExecJScript(@" var _data= " + strjsontem1 + @" ; 
//    jQuery.loadHtml('/Template/ConfirmOrderList.html').done(function (_rethtml) {
//        var tpl = HtmlUtil.htmlDecode(_rethtml);
//        laytpl(tpl).render(_data, function (render) {
//            $(""#J_OrderList"").empty().html(render);
//    " + strcalljs + @"
//        });
//    });
//      ");
//        }

        //相同运费模版计算总件数
        System.Collections.Generic.Dictionary<string, decimal> dicShopLogistAmt = new System.Collections.Generic.Dictionary<string, decimal>();
        public void ShowPayAmt(bool blExecJs = true)
        {
            dicShopLogistAmt.Clear();
            if (dsList == null || dsList.Tables[0].Rows.Count <= 0)
            {
                if (blExecJs)
                {
                    this.ExecJScript("$('#J_ActualFee').html('0.00');");
                }
                return;
            }
            decimal decTotal = 0;
            int iScoreSum = 0;
            int iScorePriceSum = 0; 
            DataRow[] arrrowtem1 = dsList.Tables[0].Select("1=1");
            var newrows = from rowt in arrrowtem1
                          group rowt by rowt["COMM_TENANT_ID"].ToString() + "-" + rowt["LOGISTICS_TEMPLATE_ID"].ToString() into g
                          orderby g.Max(p => p["COMM_TENANT_ID"].ToString()) ascending, g.Max(p => p["LOGISTICS_TEMPLATE_ID"].ToString()) ascending
                          select new
                          {
                              g.Key,
                              strCOMM_TENANT_ID = g.Max(p => p["COMM_TENANT_ID"].ToString()),
                              strLOGISTICS_TEMPLATE_ID = g.Max(p => p["LOGISTICS_TEMPLATE_ID"].ToString()),
                              iGOODS_QTY = g.Sum(p => int.Parse(p["GOODS_QTY"].ToString())),
                              iQTY_FIRST = g.Max(p => int.Parse(p["QTY_FIRST"].ToString())),
                              iPRICE_FIRST = g.Max(p => decimal.Parse(p["PRICE_FIRST"].ToString())),
                              iQTY_ADD = g.Max(p => int.Parse(p["QTY_ADD"].ToString())),
                              iPRICE_ADD = g.Max(p => decimal.Parse(p["PRICE_ADD"].ToString())),
                              iGOODS_AMT = g.Sum(p => decimal.Parse(p["GOODS_AMT"].ToString())),
                              iSCORE_NUM = g.Sum(p => int.Parse(p["SCORE_NUM"].ToString())),
                              iGOODS_STRIKE_SCORE = g.Sum(p => int.Parse(p["GOODS_STRIKE_SCORE"].ToString()))
                          };

            //System.Collections.Generic.Dictionary<string, decimal> dicdealer = new System.Collections.Generic.Dictionary<string, decimal>();
            if (newrows != null && newrows.Count() > 0)
            {
                var aa = newrows.ToArray();
                decimal decYF = 0M, decTT = 0M;
                for (int i = 0; i < aa.Length; i++)
                {
                    //单模版运价
                    decimal decLogiAmt = 0M;
                    if (aa[i].iGOODS_QTY <= aa[i].iQTY_FIRST || aa[i].iQTY_ADD == 0)
                    {
                        decLogiAmt = aa[i].iPRICE_FIRST;
                    }
                    else
                    {
                        int iaddsum = (aa[i].iGOODS_QTY - aa[i].iQTY_FIRST) / aa[i].iQTY_ADD;
                        if ((aa[i].iGOODS_QTY - aa[i].iQTY_FIRST) % aa[i].iQTY_ADD > 0)
                        {
                            iaddsum = iaddsum + 1;
                        }
                        decLogiAmt = aa[i].iPRICE_FIRST + iaddsum * aa[i].iPRICE_ADD;
                    }
                    decTotal += aa[i].iGOODS_AMT + decLogiAmt;
                    iScoreSum += aa[i].iSCORE_NUM * aa[i].iGOODS_QTY;
                    iScorePriceSum += aa[i].iGOODS_STRIKE_SCORE * aa[i].iGOODS_QTY;

                    decYF += decLogiAmt;
                    decTT += aa[i].iGOODS_AMT;

                    if (i == aa.Length - 1 || 1 < aa.Length && aa[i].strCOMM_TENANT_ID != aa[i + 1].strCOMM_TENANT_ID)
                    {
                        dicShopLogistAmt.Add(aa[i].strCOMM_TENANT_ID, decYF);
                        if (blExecJs)
                        {
                            strcalljs += "setLogisAmt('" + aa[i].strCOMM_TENANT_ID + "'," + decYF.ToString() + "," + decTT.ToString() + ");";
                            this.ExecJScript("setLogisAmt('" + aa[i].strCOMM_TENANT_ID + "'," + decYF.ToString() + "," + decTT.ToString() + ");");
                        }
                        decYF = 0M;
                        decTT = 0M;
                    }

                    //if (dicdealer.ContainsKey(aa[i].strCOMM_TENANT_ID))
                    //{
                    //    dicdealer[aa[i].strCOMM_TENANT_ID] = dicdealer[aa[i].strCOMM_TENANT_ID] + decLogiAmt;
                    //}
                    //else
                    //{
                    //    dicdealer.Add(aa[i].strCOMM_TENANT_ID, decLogiAmt);
                    //}
                }
            }


            if (blExecJs)
            {
                if (iScorePriceSum > 0)
                {
                    this.ExecJScript("$('#divscorehg').show();");
                }
                this.ExecJScript("$('#spnPAYABLE_AMT').html('" + decTotal.ToString() + "');");
                this.ExecJScript("$('#J_ActualFee').html('" + decTotal.ToString() + "');");
                this.ExecJScript("$('#spnScoreTotal').html('" + iScoreSum.ToString() + "');");
                this.ExecJScript("$('#txtPaidScoreQty').attr('max','" + iScorePriceSum.ToString() + "');");
                this.ExecJScript("$('#txtPaidScoreQty').attr('score-price','" + msBsc.SvRef.SysConst.decScoreUsePrice().ToString() + "');");
            }
        }

        public string GetAddrListHtml(string strSelId = "")
        {
            System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
            if (dsAcpList == null)
            {
                using (msBsc.AppLogic.DataAlc.CBizShpCustomerReceipt odataobj = new AppLogic.DataAlc.CBizShpCustomerReceipt())
                {
                    dsAcpList = odataobj.SelectByUserNme(msBsc.SvRef.UserInfo.Operator);
                }
            }
            for (int i = 0; i < dsAcpList.Tables[0].Rows.Count; i++)
            {
                string strtel = dsAcpList.Tables[0].Rows[i]["PHONE_NO"].ToString();
                if (strtel == string.Empty)
                {
                    strtel += dsAcpList.Tables[0].Rows[i]["AREA_CODE"].ToString() + "-" + dsAcpList.Tables[0].Rows[i]["LANDLINE_NO"].ToString() + "-" + dsAcpList.Tables[0].Rows[i]["EXTENSION_NO"].ToString();
                }
                else if (dsAcpList.Tables[0].Rows[i]["LANDLINE_NO"].ToString() != string.Empty)
                {
                    strtel += "," + dsAcpList.Tables[0].Rows[i]["AREA_CODE"].ToString() + "-" + dsAcpList.Tables[0].Rows[i]["LANDLINE_NO"].ToString() + "-" + dsAcpList.Tables[0].Rows[i]["EXTENSION_NO"].ToString();
                }

                bool blchecked = (dsAcpList.Tables[0].Rows[i]["IS_DEFAULT"].ToString() == "True" && strSelId == string.Empty || dsAcpList.Tables[0].Rows[i]["RECE_ADDRESS_ID"].ToString() == strSelId);
                string strAddrFull = dsAcpList.Tables[0].Rows[i]["ZONE_DESC"].ToString() + dsAcpList.Tables[0].Rows[i]["STREET_ADDRESS"].ToString();

                strtel = dsAcpList.Tables[0].Rows[i]["RECEIPT_NME"].ToString() + "，" + strtel;


                sbHtml.Append(@"<li rec-AddrId='" + dsAcpList.Tables[0].Rows[i]["RECE_ADDRESS_ID"].ToString() + @"' rec-provId='" + dsAcpList.Tables[0].Rows[i]["PROVINCE_ID"].ToString() + @"'><input type=""radio"" name=""address"" value=""0"" /><div class=""address-info""><p><span style="" font-weight:bold;"">收货人：</span><span class=""addr-name"">" + strtel + @"</span></p><p><span style="" font-weight:bold;"">收货地址：</span><span class=""addr-full"">" + strAddrFull + @"</span></p></div></li>");

            }
            return sbHtml.ToString();
        }

        private void doSaveOrder()
        {
            //int iOrderSum=int.Parse(this.GetPostHtValue("ORDER_COUNT")==string.Empty?"0":this.GetPostHtValue("ORDER_COUNT"));
            //if (iOrderSum <= 0)
            //{
            //    Alert("未选择商品！");
            //    return;
            //}
            string strRecerptId = this.GetParamHtValue("RECE_ADDRESS_ID");
            if (strRecerptId == string.Empty)
            {
                Alert("未选择收货地址！");
                return;
            }

            using (msBsc.AppLogic.DataAlc.CBizShpOrderForm odataobj = new AppLogic.DataAlc.CBizShpOrderForm())
            {
                DataSet dsAddr = odataobj.DataObj.QueryBySQL("SELECT * FROM SHP_CUSTOMER_RECEIPT WHERE RECE_ADDRESS_ID='" + strRecerptId + "' AND USER_NME='" + msBsc.SvRef.UserInfo.Operator + "'");
                if (dsAddr.Tables[0].Rows.Count <= 0)
                {
                    Alert("未正确选择收货地址！");
                    return;
                }
                using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo objgoods = new AppLogic.DataAlc.CBizShpGoodsInfo())
                {
                    dsList = objgoods.SelectGoodsForConfirmOrder(
                    this.GetParamHtValue("txtGoodsId")
                    , this.GetParamHtValue("txtCartId")
                    , this.GetParamHtValue("txtSrcT")
                    , this.GetParamHtValue("txtPubNId1")
                    , this.GetParamHtValue("txtPubNId2")
                    , int.Parse(this.GetParamHtValue("txtBuyQty"))
                    , this.GetParamHtValue("txtPlaceId"));
                }
                ShowPayAmt(false);
                string strOrderNos = "";
                foreach (string sKey in dicShopLogistAmt.Keys)
                {
                    DataSet ds = new msBsc.Xsd.DataTds.CDmShpOrderForm();
                    DataSet dsItem = new msBsc.Xsd.DataTds.CDmShpOrderFormList();
                    //string strOrderId = "";
                    DataRow[] arrrowtm = dsList.Tables[0].Select("COMM_TENANT_ID='" + sKey + "'");

                    DataSet dsshop = odataobj.DataObj.QueryBySQL(@"
    SELECT
    PROVINCE_ID
    ,CITY_ID
    ,AREA_ID
    ,ZONE_DESC
    ,CONTACTS
    ,CONTACTS_EMAIL
    ,CONTACTS_TEL
    ,CONTACTS_ADDRESS
    ,CONTACTS_PHONE FROM SHP_COMMERCIAL_TENANT_INFO WHERE COMM_TENANT_ID='" + sKey + "'");

                    DataRow drnew = ds.Tables[0].NewRow();
                    drnew["ORDER_FORM_ID"] = odataobj.DataObj.NewID();
                    drnew["USER_NME"] = msBsc.SvRef.UserInfo.Operator;
                    drnew["ORDER_FORM_NO"] = msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
                    drnew["COMM_TENANT_ID"] = sKey;
                    //DataSet dsDealer = odataobj.DataObj.QueryBySQL("SELECT COMM_TENANT_NME,USER_NME FROM SHP_COMMERCIAL_TENANT_INFO WHERE COMM_TENANT_ID='" + drnew["COMM_TENANT_ID"].ToString() + "' ");
                    //if (dsDealer.Tables[0].Rows.Count <= 0)
                    //{
                    //    Alert("传入的参数错误，商家信息未找到！");
                    //    return;
                    //}
                    if (arrrowtm[0]["USER_NME"].ToString().ToUpper() == msBsc.SvRef.UserInfo.Operator.ToUpper())
                    {
                        Alert("不能自己购买自己的商品！");
                        return;
                    }

                    drnew["COMM_TENANT_NME"] = arrrowtm[0]["COMM_TENANT_NME"];
                    drnew["COMM_USER_NME"] = arrrowtm[0]["USER_NME"];
                    drnew["FROM_PROVINCE_ID"] = dsshop.Tables[0].Rows[0]["PROVINCE_ID"];
                    drnew["FROM_CITY_ID"] = dsshop.Tables[0].Rows[0]["CITY_ID"];
                    drnew["FROM_AREA_ID"] = dsshop.Tables[0].Rows[0]["AREA_ID"];
                    drnew["FROM_ZONE_DESC"] = dsshop.Tables[0].Rows[0]["ZONE_DESC"];
                    drnew["FROM_STREET_ADDRESS"] = dsshop.Tables[0].Rows[0]["CONTACTS_ADDRESS"];
                    drnew["FROM_SENDER_NME"] = dsshop.Tables[0].Rows[0]["CONTACTS"];
                    drnew["FROM_PHONE_NO"] = dsshop.Tables[0].Rows[0]["CONTACTS_PHONE"];
                    drnew["FROM_LANDLINE_NO"] = dsshop.Tables[0].Rows[0]["CONTACTS_TEL"];


                    drnew["TO_PROVINCE_ID"] = dsAddr.Tables[0].Rows[0]["PROVINCE_ID"];
                    drnew["TO_CITY_ID"] = dsAddr.Tables[0].Rows[0]["CITY_ID"];
                    drnew["TO_AREA_ID"] = dsAddr.Tables[0].Rows[0]["AREA_ID"];
                    drnew["TO_ZONE_DESC"] = dsAddr.Tables[0].Rows[0]["ZONE_DESC"];
                    drnew["TO_STREET_ADDRESS"] = dsAddr.Tables[0].Rows[0]["STREET_ADDRESS"];
                    drnew["TO_ZIP_CODE"] = dsAddr.Tables[0].Rows[0]["ZIP_CODE"];
                    drnew["TO_RECEIPT_NME"] = dsAddr.Tables[0].Rows[0]["RECEIPT_NME"];
                    drnew["TO_PHONE_NO"] = dsAddr.Tables[0].Rows[0]["PHONE_NO"];
                    if (dsAddr.Tables[0].Rows[0]["LANDLINE_NO"].ToString() != string.Empty)
                    {
                        drnew["TO_LANDLINE_NO"] = dsAddr.Tables[0].Rows[0]["AREA_CODE"].ToString() + "-" + dsAddr.Tables[0].Rows[0]["LANDLINE_NO"].ToString() + (dsAddr.Tables[0].Rows[0]["EXTENSION_NO"].ToString() != string.Empty ? "-" + dsAddr.Tables[0].Rows[0]["EXTENSION_NO"].ToString() : "");
                    }
                    else
                    {
                        drnew["TO_LANDLINE_NO"] = "";
                    }
                    drnew["DELIVER_TYPE_CID"] = "普通快递";

                    drnew["BUY_MEMO"] = this.GetParamHtValue("BUY_MEMO_" + sKey);
                     
                    decimal decTotal = 0, decAmt = 0;
                    int iRvcScoreTotal = 0;
                    string strGoodsNme = "";
                    for (int r = 0; r < arrrowtm.Length; r++)
                    {
                        string strGoodsId = arrrowtm[r]["GOODS_ID"].ToString();
                        //DataRow[] arrrowtem1 = dsNmList.Tables[0].Select("GOODS_ID='" + strGoodsId + "'");
                        //if (arrrowtem1.Length <= 0)
                        //{
                        //    continue;
                        //}
                        //int iGoodsQty = int.Parse(this.GetPostHtValue("GOODS_QTY_" + i.ToString() + "_" + r.ToString()) == string.Empty ? "1" : this.GetPostHtValue("GOODS_QTY_" + i.ToString() + "_" + r.ToString()));
                        DataRow dritem = dsItem.Tables[0].NewRow();
                        dritem["ORDER_LIST_ID"] = odataobj.DataObj.NewID();
                        dritem["ORDER_FORM_ID"] = drnew["ORDER_FORM_ID"];
                        dritem["SEQ_NUM"] = r;
                        dritem["GOODS_ID"] = strGoodsId;
                        dritem["GOODS_NME"] = arrrowtm[r]["GOODS_NME"];
                        dritem["IMG_URL"] = arrrowtm[r]["IMG_URL"];
                        dritem["PUB_NORMS_ID"] = arrrowtm[r]["PUB_NORMS_ID"];
                        dritem["NORMS_DESC"] = arrrowtm[r]["NORMS_DESC"].ToString().Substring(1);
                        if (arrrowtm[r]["IS_DEL"].ToString() == "1")
                        {
                            this.ExecJScript("window.location.reload(true) ;");
                            throw new Exception("商品已失效或库存不足，无法确认订单，请返回重新选择");
                        }
                        dritem["GOODS_QTY"] = arrrowtm[r]["GOODS_QTY"];
                        dritem["GOODS_STRIKE_PRICE"] = arrrowtm[r]["GOODS_STRIKE_PRICE"];
                        dritem["GOODS_STRIKE_SCORE"] = arrrowtm[r]["GOODS_STRIKE_SCORE"];

                        strGoodsNme += strGoodsNme == string.Empty ? dritem["GOODS_NME"].ToString() : "," + dritem["GOODS_NME"].ToString();
                        decAmt += (decimal)arrrowtm[r]["GOODS_AMT"];
                        iRvcScoreTotal += (int)arrrowtm[r]["SCORE_NUM"] * (int)dritem["GOODS_QTY"];
                        //decYf += decimal.Parse(arrrowtem1[0]["FREIGHT"].ToString() == string.Empty ? "0.00" : arrrowtem1[0]["FREIGHT"].ToString());
                        dsItem.Tables[0].Rows.Add(dritem);
                    }
                    decTotal += (decAmt + dicShopLogistAmt[sKey]);
                    drnew["GOODS_AMT"] = decAmt;
                    drnew["LOGISTICS_AMT"] = dicShopLogistAmt[sKey];
                    drnew["DISCOUNT_AMT"] = 0M;
                    drnew["PAYABLE_AMT"] = decTotal;

                    if (strGoodsNme.Length > 25)
                    {
                        strGoodsNme = strGoodsNme.Substring(0, 25);
                    }
                    drnew["ORDER_FORM_NME"] = strGoodsNme;

                    drnew["PAID_SCORE_QTY"] = int.Parse(this.GetParamHtValue("txtPaidScoreQty") == string.Empty ? "0" : this.GetParamHtValue("txtPaidScoreQty"));
                    drnew["PAID_SCORE_AMT"] = (int)drnew["PAID_SCORE_QTY"] * msBsc.SvRef.SysConst.decScoreUsePrice();
                    drnew["RCV_SCORE_QTY"] = iRvcScoreTotal;

                    drnew["PAID_AMT"] = (decimal)drnew["PAYABLE_AMT"] - (decimal)drnew["PAID_SCORE_AMT"];
                    drnew["PAID_MODE_CID"] = "";
                    drnew["TRADE_STATUS_TXT"] = "等待买家付款";
                    drnew["AFTER_SVC_STATUS_TXT"] = "";
                    ds.Tables[0].Rows.Add(drnew);

                    strOrderNos += strOrderNos == string.Empty ? drnew["ORDER_FORM_NO"].ToString() : "," + drnew["ORDER_FORM_NO"].ToString();


                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpOrderFormList objItem = new AppLogic.DataAlc.CBizShpOrderFormList())
                        {
                            objItem.Update(dsItem);
                        }
                        odataobj.Update(ds);
                        //using (msBsc.AppLogic.DataAlc.CBizSysUser ouser = new AppLogic.DataAlc.CBizSysUser())
                        //{
                        //    ouser.UpdateOrderStatistic(msBsc.SvRef.UserInfo.Operator);
                        //}

                        if (this.GetParamHtValue("txtCartId") != string.Empty)
                        {
                            odataobj.DataObj.ExecuteBySQL("DELETE SHP_CUSTOMER_CART WHERE USER_NME='" + msBsc.SvRef.UserInfo.Operator + "' AND CART_ORDER_ID IN ('" + this.GetParamHtValue("txtCartId").Replace(",", "','") + "')");
                        }

                        ts.Complete();
                    }
                }

                this.ExecJScript("layer.msg('已成功提交订单！',1,{type:1,shade:false});");
                this.ExecJScript("window.location.href = '/mb_PayCashier.htm?ID=" + strOrderNos + "';");
            }
        }

        private void doSaveAddr()
        {
            {
                using (msBsc.AppLogic.DataAlc.CBizShpCustomerReceipt odataobj = new AppLogic.DataAlc.CBizShpCustomerReceipt())
                {
                    DataSet odata;
                    DataRow drnew;
                    if (GetPostHtValue("RECE_ADDRESS_ID") == string.Empty)
                    {
                        odata = new Xsd.DataTds.CDmShpCustomerReceipt();
                        drnew = odata.Tables[0].NewRow();
                        drnew["RECE_ADDRESS_ID"] = odataobj.DataObj.NewID();
                        drnew["USER_NME"] = msBsc.SvRef.UserInfo.Operator;
                        odata.Tables[0].Rows.Add(drnew);
                    }
                    else
                    {
                        odata = odataobj.SelectById(GetPostHtValue("RECE_ADDRESS_ID"));
                        if (odata.Tables[0].Rows.Count <= 0)
                        {
                            odata = new Xsd.DataTds.CDmShpCustomerReceipt();
                            drnew = odata.Tables[0].NewRow();
                            drnew["RECE_ADDRESS_ID"] = odataobj.DataObj.NewID();
                            drnew["USER_NME"] = msBsc.SvRef.UserInfo.Operator;
                            odata.Tables[0].Rows.Add(drnew);
                        }
                        else
                        {
                            drnew = odata.Tables[0].Rows[0];
                        }
                    }

                    msBsc.AppLogic.Cfg.HttpTools.CopyHashToDataRow(this.htPostDataRow, drnew);

                    if (drnew["PROVINCE_ID"].ToString() == string.Empty || drnew["CITY_ID"].ToString() == string.Empty || drnew["AREA_ID"].ToString() == string.Empty)
                    {
                        Alert("请选择所在地区！");
                        return;
                    }
                    if (drnew["STREET_ADDRESS"].ToString() == string.Empty || drnew["STREET_ADDRESS"].ToString().Length < 5 || drnew["STREET_ADDRESS"].ToString().Length > 120)
                    {
                        Alert("请填写详细地址，不需要重复填写省市区，必须大于5个字符，小于120个字符！");
                        return;
                    }
                    if (drnew["ZIP_CODE"].ToString() == string.Empty || drnew["ZIP_CODE"].ToString().Length != 6)
                    {
                        Alert("请填写邮政编码， 必须6个字符！");
                        return;
                    }
                    if (drnew["RECEIPT_NME"].ToString() == string.Empty || drnew["RECEIPT_NME"].ToString().Length < 2 || drnew["RECEIPT_NME"].ToString().Length > 20)
                    {
                        Alert("请填写收货人，收货人姓名姓名应为2-20个字符，一个汉字为两个字符！");
                        return;
                    }
                    if (drnew["PHONE_NO"].ToString() == string.Empty && drnew["LANDLINE_NO"].ToString() == string.Empty)
                    {
                        Alert("电话号码、手机号选填一项！");
                        return;
                    }
                    if (drnew["LANDLINE_NO"].ToString() != string.Empty && drnew["AREA_CODE"].ToString() == string.Empty)
                    {
                        Alert("请填写电话号码区号！");
                        return;
                    }

                    odataobj.Update(odata);

                    if (drnew["IS_DEFAULT"].ToString() == "True")
                    {
                        odataobj.DataObj.ExecuteBySQL("UPDATE SHP_CUSTOMER_RECEIPT SET IS_DEFAULT=1 WHERE RECE_ADDRESS_ID='" + drnew["RECE_ADDRESS_ID"].ToString() + "'");
                        odataobj.DataObj.ExecuteBySQL("UPDATE SHP_CUSTOMER_RECEIPT SET IS_DEFAULT=0 WHERE RECE_ADDRESS_ID<>'" + drnew["RECE_ADDRESS_ID"].ToString() + "'");
                    }

                    this.ExecJScript("showaddnewaddr();");
                    this.ExecJScript("$('#addresslist').html('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(GetAddrListHtml("")) + "');"); 
                    this.ExecJScript("$('#addresslist').stop().show('fast');");
                }
            }
        }

        public override void DoAction()
        {
            if (this.strAction == "updateaddress")
            {
                if (dsList == null)
                {
                    using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo objgoods = new AppLogic.DataAlc.CBizShpGoodsInfo())
                    {
                        dsList = objgoods.SelectGoodsForConfirmOrder(
                    this.GetParamHtValue("txtGoodsId")
                    , this.GetParamHtValue("txtCartId")
                    , this.GetParamHtValue("txtSrcT")
                    , this.GetParamHtValue("txtPubNId1")
                    , this.GetParamHtValue("txtPubNId2")
                    , int.Parse(this.GetParamHtValue("txtBuyQty"))
                    , this.GetParamHtValue("txtPlaceId"));
                    }
                }
                ShowPayAmt(true);
                //this.ExecJScript("$('#address-list').html('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(GetAddrListHtml(GetParamHtValue("SEL_ID"))) + "');");
                //this.ExecJScript("updateorderaddr();");
            }
            else if (this.strAction == "dplPROVINCE_ID_change")
            {
                BoundFromCity(this.GetParamHtValue("PROVINCE_ID"));
            }
            else if (this.strAction == "dplCITY_ID_change")
            {
                BoundArea(this.GetParamHtValue("CITY_ID"));
            }
            else if (this.strAction == "doSaveAddr")
            {
                doSaveAddr( );
            } 
            //else if (this.strAction == "doloadGoodsList")
            //{
            //    ShowPayAmt();
            //    loadGoodsList(
            //        this.GetParamHtValue("txtGoodsId")
            //        , this.GetParamHtValue("txtCartId")
            //        , this.GetParamHtValue("txtSrcT")
            //        , this.GetParamHtValue("txtPubNId1")
            //        , this.GetParamHtValue("txtPubNId2")
            //        , int.Parse(this.GetParamHtValue("txtBuyQty"))
            //        , this.GetParamHtValue("txtPlaceId"));
            //    if (this.GetParamHtValue("RECE_ADDRESS_ID") != string.Empty)
            //    {
            //        this.ExecJScript("$('#J_Go').removeClass('btn-go-disabled');");
            //    }
            //    DataRow[] arrrowtem2 = dsList.Tables[0].Select("IS_DEL='1'");
            //    if (arrrowtem2.Length > 0)
            //    {
            //        this.ExecJScript("$('#J_Go').removeClass('btn-go-disabled').addClass('btn-go-disabled');");
            //        this.ExecJScript("$('#divErrShow').html('" + msBsc.AppLogic.Cfg.HttpTools.stringToJson("商品已失效或库存不足，无法确认订单，请返回重新选择！") + "');");
            //    }
            //}
            else if (this.strAction == "doSaveOrder")
            {
                doSaveOrder();
            }
        }
    }
}